<!--
 * @author  dumeng
 新建/编辑课程
-->
<template>
  <div class="course-create">
    <div class="course-create-title">新建/编辑课程</div>
    <section v-loading="loading" class="course-create-main">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="150px"
        class="form"
      >
        <!-- <el-form-item label="版本选择" prop="courseTemplate">
          <el-radio-group v-model="form.courseTemplate">
            <el-radio
              v-for="v in dict.KCMB"
              :key="v.dictValue"
              :label="v.dictValue"
            >{{ v.dictName }}</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="课程名称" prop="courseName">
          <el-input
            v-model="form.courseName"
            placeholder="请输入课程名称"
            maxlength="40"
            :disabled="courseBelong"
          />
        </el-form-item>
        <!-- <el-form-item label="课程来源">
          <el-input
            v-model="form.courseSource"
            placeholder="请输入课程来源"
            maxlength="50"
            :disabled="courseBelong"
          />
        </el-form-item> -->
        <el-form-item label="课程分类" prop="courseClassify">
          <el-cascader
            v-if="showClassify"
            ref="classify"
            v-model="form.courseClassify"
            style="width: 100%"
            clearable
            :props="createClassifyProps"
            :options="classifyOptions"
          />
        </el-form-item>
        <el-form-item label="课程封面" prop="courseImg" required>
          <image-upload
            :key="uploadImg.imagecropperKey"
            v-model="form.courseImg"
            :preview-id="uploadImg.viewId"
            :forever="true"
            :width="342"
            :view="uploadImg.view"
            :height="190"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
            :is-oss="isOss"
            @changeOssPath="
              (path) => {
                uploadImg.viewId = path;
              }
            "
          />
          <!--          <el-image-->
          <!--            v-else-->
          <!--            style="width: 342px; height: 190px"-->
          <!--            :src="uploadImg.viewId"-->
          <!--            :preview-src-list="[uploadImg.viewId]"-->
          <!--          />-->
        </el-form-item>
        <!-- <el-form-item label="关键词" prop="courseKeyword">
          <el-input
            v-model="form.courseKeyword"
            placeholder="请输入关键词"
            maxlength="100"
          />
        </el-form-item> -->
        <el-form-item label="标签:">
          <el-checkbox-group
            v-model="form.subjectCategory"
            class="course-tag"
            size="mini"
          >
            <el-checkbox v-for="(i, n) in tagList" :key="n" :label="i" border />
          </el-checkbox-group>
          <el-tag
            v-for="tag in form.courseLabel"
            :key="tag"
            class="item-course-tag"
            closable
            :disable-transitions="false"
            @close="handleCloseTag(tag)"
          >{{ tag }}
          </el-tag>
          <div>
            <el-input
              ref="tagInput"
              v-model="tagInputValue"
              class="input-new-tag"
              style="width: 80%"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            />
            <span class="tip"><i class="el-icon-info" />输入完成后请回车</span>
          </div>
        </el-form-item>
        <el-form-item label="课程介绍" prop="courseIntro">
          <tinymce v-if="isTinymce" v-model="form.courseIntro" :is-oss="isOss" :height="300" />
        </el-form-item>
        <el-form-item label="简介" prop="courseIntroduce">
          <el-input
            v-model="form.courseIntroduce"
            :rows="6"
            type="textarea"
            maxlength="3000"
            show-word-limit
            :disabled="courseBelong"
          />
        </el-form-item>
        <!-- <el-form-item label="讲师介绍" prop="extend2">
          <el-input v-model.trim="form.extend2" maxlength="1000" placeholder="" show-word-limit type="textarea" :rows="6" />
        </el-form-item> -->
        <el-form-item label="选择讲师" prop="extend3">
          <div>
            <el-button
              class="button-new-tag"
              size="small"
              @click="showInputRwys"
            >请选择讲师</el-button>
          </div>
          <div>
            <el-tag
              v-for="tag in form.extend3"
              :key="tag.id"
              closable
              @close="handleCloses(tag)"
            >
              {{ tag.name }}
            </el-tag>
          </div>
        </el-form-item>
        <!-- <el-form-item label="人物信息展示方式" prop="extend4">
          <el-select v-model="form.extend4" placeholder="请选择人物信息展示方式">
            <el-option v-for="item in dict['RWXXYSLX']" :key="item.dictValue" :label="item.dictName" :value="item.dictValue" />
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="是否推荐" prop="isRecommend">
          <el-radio-group v-model="form.isRecommend">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否允许评论" prop="isDiscuss">
          <el-radio-group v-model="form.isDiscuss">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="排序" prop="sort">
          <el-input
            v-model.number="form.sort"
            placeholder="请输入排序号（值越大，越靠前）"
            maxlength="5"
          />
        </el-form-item>
      </el-form>
    </section>
    <section class="course-create-footer">
      <el-button
        style="padding: 10px 30px"
        @click="handleBack"
      >取 消</el-button>
      <el-button type="primary" @click="onSubmint()">确 定</el-button>
    </section>
    <!-- 选择导师 -->
    <el-dialog
      v-el-drag-dialog
      title="选择讲师"
      :visible.sync="dialogFormVisibles"
      center
      fullscreen
      :close-on-click-modal="false"
    >
      <add-users
        ref="resetAll"
        v-loading.fullscreen.lock="fullscreenLoadings"
        :before-list="beforeLists"
        @userData="userDatas"
      />
      <div slot="footer" class="dialog-footer">
        <el-button
          style="padding: 8px 30px"
          @click="dialogFormVisibles = false"
        >取消</el-button>
        <el-button
          style="padding: 8px 30px"
          type="primary"
          @click="insertUsers()"
        >确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import ImageUpload from '@/components/ImageUpload'
import {
  getCon,
  getClassifyTree,
  insert,
  update,
  get,
  getSubject,
  getDictByCode
} from '../api/create'
import { specialText, number } from '@/utils/validate'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import addUsers from '@/views/trainingArea/trainingManage/components/addUser' // Secondary package based on el-pagination
export default {
  name: 'CourseCreate',
  components: { ImageUpload, addUsers, Tinymce },
  directives: { elDragDialog },
  data() {
    return {
      isTinymce: false, // 编辑的时候要拿到数据在显示富文本组件
      isOss: sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG') || false,
      loading: false,
      dialogFormVisibles: false,
      fullscreenLoadings: false,
      beforeLists: [],
      dialogMultipleSelections: [],
      form: {
        id: '',
        deptId: '-1',
        courseName: '',
        courseSource: '',
        courseClassify: '',
        courseImg: '',
        courseKeyword: '',
        courseIntro: '',
        courseIntroduce: '',
        extend2: '',
        extend3: [], // 选择导师
        extend4: '', // 人物信息展示类型
        isRecommend: '0',
        isDiscuss: 0,
        courseTemplate: 0,
        subjectCategory: [],
        courseLabel: [],
        sort: '',
        status: 'KCZT02',
        courseType: 'KCLX01'
      },
      rules: {
        courseName: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
          { validator: specialText, trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
          { validator: number, trigger: 'blur' }
        ],
        courseSource: [
          { required: true, message: '请输入课程来源', trigger: 'blur' }
        ],
        courseClassify: [
          { required: true, message: '请选择课程分类', trigger: 'change' }
        ],
        courseImg: [
          { required: true, message: '请上传课程封面', trigger: 'change' }
        ],
        // extend3: [
        //   {
        //     required: true,
        //     message: '请选择导师',
        //     trigger: 'change',
        //     validator: (rule, value, callback) => {
        //       if (value.length === 0) {
        //         callback(new Error('请选择导师'))
        //       } else {
        //         callback()
        //       }
        //     }
        //   }
        // ],
        /* courseIntroduce: [
          { required: true, message: '请输入简介', trigger: 'blur' }
        ],*/
        // isRecommend: [
        //   { required: true, message: '请选择是否推荐', trigger: 'change' }
        // ],
        // isDiscuss: [
        //   { required: true, message: '请选择是否允许评论', trigger: 'change' }
        // ],
        courseTemplate: [
          { required: true, message: '请选择版本', trigger: 'change' }
        ]
      },
      inputDuration: true, // 是否禁用输入课程时长
      tagInputVisible: false,
      tagInputValue: '',
      createClassifyProps: {
        label: 'classifyName',
        value: 'id',
        checkStrictly: true
      },
      classifyOptions: [],
      showClassify: false,
      state: 'create',
      uploadImg: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0
      },
      preview: {
        state: false,
        fileId: '',
        fileType: 1
      },
      Onece: false,
      tagList: [],
      dict: {
        KCMB: []
      },
      isOss: sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG') || false,
      backUrl: '',
      activeTab: '',
      courseBelong: false
    }
  },
  watch: {
    'form.classifyIds': {
      handler(newName, oldName) {
        if (this.$refs.classify) {
          this.$refs.classify.dropDownVisible = false
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.state = this.$route.query.type === 'u' ? 'update' : 'create'
    this.Onece = this.$route.query.t === 'courseware'
    this.activeTab = this.$route.query.activeTab
    this.getClassifyOption()
    this.getDict('KCMB')
    if (this.Onece) {
      this.backUrl = this.Onece
        ? '/skill/course/courseware'
        : '/skill/course/index'
      return this.getInit()
    }
    if (this.$route.query.type === 'u') {
      this.isTinymce = false
      this.backUrl = '/skill/course/index'
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      getCon({ id: 'COURSE_TAG' })
        .then((res) => {
          loading.close()
          this.tagList = res.data.data.configValue
            ? res.data.data.configValue.split(',')
            : []
          if (!this.$route.query.i) {
            this.$message({
              showClose: true,
              message: '参数异常！',
              type: 'warning',
              onClose: () => {
                this.$router.back()
              }
            })
          } else {
            this.getData(this.$route.query.i)
          }
        })
        .catch((err) => {
          loading.close(err)
        })
    } else {
      this.isTinymce = true
      this.backUrl = this.Onece
        ? '/skill/course/courseware'
        : '/skill/course/index'
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      getCon({ id: 'COURSE_TAG' })
        .then((res) => {
          this.tagList = res.data.data.configValue.split(',') || []
          loading.close()
        })
        .catch(loading.close)
      this.showClassify = true
    }
  },
  methods: {
    /**
     * 获取字典
     * @param KCMB
     * @returns {Promise<any>}
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code)
          .then((res) => {
            this.form.courseTemplate = res.data.data[0].list[2].id
            this.dict[code] =
              res.data.data && res.data.data.length > 0
                ? res.data.data[0].list
                : []
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 删除导师
    handleCloses(tag) {
      this.form.extend3.splice(this.form.extend3.indexOf(tag), 1)
    },
    // 选择人物元素
    userDatas(val) {
      this.dialogMultipleSelections = val
    },
    // 选择选择导师
    showInputRwys() {
      this.dialogFormVisibles = true
    },
    // 确定选择的人员
    insertUsers() {
      if (this.dialogMultipleSelections.length > 0) {
        // console.log(this.dialogMultipleSelections, 'this.dialogMultipleSelectionssssssssssssssssssss')
        const dataBzr = this.dialogMultipleSelections.map((item) => {
          return {
            id: item.id,
            name: item.name
          }
        })
        this.$set(this.form, 'extend3', dataBzr)
        this.dialogListLoadings = true
        this.dialogFormVisibles = false
      } else {
        this.$message({
          message: '请选择导师！',
          type: 'warning'
        })
      }
    },
    /**
     * 获取课程分类
     */
    getClassifyOption() {
      return new Promise((resolve, reject) => {
        getClassifyTree({ classifyType: 'JNZQFL01', status: 'ZT01' })
          .then(({ data }) => {
            this.classifyOptions = data.data || []
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    onSubmint() {
      // return
      if (this.state === 'create') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const params = JSON.parse(
              JSON.stringify(Object.assign({}, this.form))
            );
            (params['docentId'] = this.form.extend3
              .map((item) => item.id)
              .toString()),
            (params['extend3'] = JSON.stringify(this.form.extend3))
            const courseLable = [
              ...params['subjectCategory'],
              ...params['courseLabel']
            ].join(',')
            params['courseClassify'] =
              this.form.courseClassify.length > 0
                ? this.form.courseClassify[this.form.courseClassify.length - 1]
                : ''
            params['courseLabel'] = courseLable
            if (params['courseLabel'].length > 100) {
              return this.$message({
                type: 'warning',
                message: '标签总字数不能超过100个字！'
              })
            }
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            delete params.subjectCategory
            if (params['courseImg'].startsWith('http')) {
              delete params.courseImg
            }
            return new Promise((resolve, reject) => {
              insert(params)
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.replace({
                    path: this.backUrl,
                    query: {
                      activeTab: this.activeTab
                    }
                  })
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const params = JSON.parse(
              JSON.stringify(Object.assign({}, this.form))
            );
            (params['docentId'] = this.form.extend3
              .map((item) => item.id)
              .toString()),
            (params['extend3'] = JSON.stringify(this.form.extend3))
            const courseLable = [
              ...params['subjectCategory'],
              ...params['courseLabel']
            ].join(',')
            params['courseClassify'] =
              this.form.courseClassify.length > 0
                ? this.form.courseClassify[this.form.courseClassify.length - 1]
                : ''
            params['courseLabel'] = courseLable
            if (params['courseLabel'].length > 100) {
              return this.$message({
                type: 'warning',
                message: '标签总字数不能超过100个字！'
              })
            }
            delete params.subjectCategory
            if (params['courseImg'].startsWith('http')) {
              delete params.courseImg
            }
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            return new Promise((resolve, reject) => {
              update(params)
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '修改成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.replace({
                    path: this.backUrl,
                    query: {
                      activeTab: this.activeTab
                    }
                  })
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            return false
          }
        })
      }
    },
    /**
     * 显示课程标签输入框
     */
    showTagInput() {
      this.tagInputVisible = true
      this.$nextTick((_) => {
        this.$refs.tagInput.$refs.input.focus()
      })
    },
    /**
     * 确认课程标签输入框内容
     */
    handleInputConfirm() {
      const inputValue = this.tagInputValue.trim().replace(/,|，/g, '')

      if (inputValue) {
        this.form.courseLabel.push(inputValue)
      }
      this.tagInputVisible = false
      this.tagInputValue = ''
    },
    /**
     * 确认课程标签
     */
    handleCloseTag(tag) {
      this.form.courseLabel.splice(this.form.courseLabel.indexOf(tag), 1)
    },
    /**
     * 根编辑回显
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: id })
          .then((res) => {
            loading.close()
            const data = res.data.data
            const subJect = []
            for (const key in this.form) {
              if (key === 'courseImg') {
                this.form[key] = data.courseImg
                this.uploadImg.viewId = data.courseImgUrl
              } else if (key === 'courseClassify') {
                const idsArr =
                  (data.courseClassifyIds &&
                    data.courseClassifyIds.split(',')) ||
                  []
                this.form[key] = idsArr
              } else if (key === 'courseLabel') {
                const arr = this.tagList
                this.form[key] =
                  (data.courseLabel && data.courseLabel.split(',')) || []
                for (const i of this.form[key]) {
                  if (arr.includes(i)) {
                    subJect.push(i)
                  }
                }
                this.form[key] = this.form[key].filter((i) => !arr.includes(i))
              } else if (key === 'extend3') {
                this.form.extend3.push({ id: data.docentId, name: data.docentName })
              } else if (key === 'courseId') {
                this.form[key] = data.courseId
                this.$set(this.uploadFile, 'file', {
                  name: '已上传',
                  id: data.courseId
                })
              } else {
                this.form[key] = data[key]
              }
            }
            this.form['subjectCategory'] = subJect

            this.courseBelong = res.data.data.courseBelong === '0'
            this.$nextTick(() => {
              this.showClassify = true
            })
            this.isTinymce = true
          })
          .catch((error) => {
            this.isTinymce = true
            loading.close()
            reject(error)
          })
      })
    },
    getInit() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })

      getCon({ id: 'COURSE_TAG' })
        .then((res) => {
          this.tagList = res.data.data.configValue.split(',') || []
          getSubject({ id: this.$route.query.i })
            .then((res) => {
              loading.close()
              const data = res.data.data
              const subJect = []
              this.form.courseSource = data.subjectSource
              this.form.courseName = data.subjectName
              this.form.courseImg = data.subjectImg
              this.uploadImg.viewId = data.subjectImgUrl
              this.form.courseKeyword = data.subjectKeyword
              this.form.courseIntroduce = data.subjectIntroduce
              const arr = this.tagList
              this.form.courseLabel =
                (data.subjectLabel && data.subjectLabel.split(',')) || []
              for (const i of this.form.courseLabel) {
                if (arr.includes(i)) {
                  subJect.push(i)
                }
              }
              this.form.courseLabel =
                (data.subjectLabel && data.subjectLabel.split(',')) || []
              this.form.courseLabel = this.form.courseLabel.filter(
                (i) => !arr.includes(i)
              )
              this.form['subjectCategory'] = subJect
              this.form.courseClassify =
                (data.subjectClassifyIds &&
                  data.subjectClassifyIds.split(',')) ||
                []
              this.showClassify = true
            })
            .catch((err) => {
              console.log(err)
              loading.close()
            })
          this.form.subjectId = this.$route.query.i
        })
        .catch(loading.close())
    },
    handleBack() {
      this.$router.replace({
        path: this.backUrl,
        query: {
          activeTab: this.activeTab
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.course-create {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;

  .course-create-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;

    &:before {
      content: "";
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .course-create-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;

    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }

    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }

    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }

    &:hover {
      overflow: auto;
    }

    .form {
      width: 1000px !important;
      margin: 0 auto;

      .el-select {
        width: 100%;
      }

      .line {
        text-align: center;
      }

      .course-tag {
        display: inline-block;
        vertical-align: 1px;

        .el-checkbox.is-bordered + .el-checkbox.is-bordered {
          margin-left: 0;
        }

        .el-checkbox {
          margin-right: 10px;
          height: 32px;

          .el-checkbox__label {
            line-height: 24px;
          }
        }

        .input-new-tag {
          margin-top: 6px;
        }
      }
      .item-course-tag {
        height: auto;
        white-space: normal;
        max-width: 800px;
        word-break: break-all;
      }
    }

    .select-data {
      display: inline-block;
      background: rgba(246, 246, 246, 1);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: rgba(51, 51, 51, 1);
      padding: 0 10px;
      margin-right: 5px;
      margin-bottom: 8px;

      i {
        cursor: pointer;
        padding-left: 5px;
      }
    }

    .selectbtn {
      display: inline-block;
      width: 120px;
      background: rgba(255, 255, 255, 1);
      @include border-color(1px, dotted, $mainColor);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      @include font-color($mainColor);
      text-align: center;
      cursor: pointer;
    }
  }

  .course-create-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }
}
</style>
<style lang="scss">
.course-create {
  .classify-tree-con {
    position: relative;
    height: 400px;
    overflow: hidden;

    .classify-tree-con-scrollbar {
      overflow: hidden;

      .el-scrollbar__wrap {
        max-height: 381px;
      }
    }

    .custom-tree-node {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      width: 100%;

      .tree-node-txt {
        flex: 1;
      }
    }
  }

  .el-tag--medium {
    line-height: 32px;
    height: 32px;

    & + .el-tag--medium {
      margin-left: 10px;
    }
  }

  .tip {
    font-size: 14px;
    color: $mainColor;
    margin-bottom: 10px;
  }
}
</style>
